/**
 * Created by wzh on 2016/8/8.
 */
swan_pc
    .controller("OrgAddressBookController",function($scope,$rootScope,orgCompany,OrgContact,$state) {
        $scope.loadDepartment=function(){
            orgCompany.query({},function() {
                orgCompany.query({page: 0, size: 500, sort: ['id' + ',' + 'asc', 'id']}, function (result) {
                    _.forEach(result, function (item) {
                        if (item.isMe == true && item.organizationId == $rootScope.organization.id) {
                            orgCompany.queryAll({infoid: item.id}, function (item) {
                                $scope.selfOrg = item;
                                $scope.departments=[];
                                $scope.departmentsList=[];
                                _.forEach(item.departments,function(item){
                                    if(item.parentDepartmentId==null){
                                        $scope.departments.push(item)
                                        $scope.departmentsList.push(item)
                                    }
                                });
                                for (var i=0;i<$scope.departmentsList.length;i++){
                                    if ($scope.departmentsList[i].subDepartments!=undefined&&$scope.departmentsList[i].subDepartments.length>0){
                                        _.forEach($scope.departmentsList[i].subDepartments,function(item){
                                            $scope.departmentsList.push(item)
                                        })
                                    }
                                }
                                $scope.myDraw();
                            }, function () {
                                alert("网络连接错误")
                            })
                        }
                    })
                }, function () {
                    alert("网络连接错误")
                })
            })
        };
        $scope.showDepartment=true;
        $scope.loadContact=function(){
            OrgContact.query({page:0, size: 5000, sort: ['id' + ',' + 'asc', 'id']},function(result){
                $scope.orgContactList=result;
            },function(result){
            })
        };
        $scope.loadAll=function(){
            $scope.loadDepartment();
            $scope.loadContact();
        }
        if ($rootScope.organization==undefined) $state.go("changeOrg");
        else $scope.loadAll()
        //绘制图表
        $scope.getRow=function(department){
            var row=[];
            row.push({
                v:department.id.toString(),
                f:'<div>'+department.name+'</div>'
            })
            row.push(department.parentDepartmentId!=undefined?department.parentDepartmentId.toString():'0')
            row.push(department.duty)
            return row;
        }
        $scope.getRows=function(departments,rows){
            _.forEach(departments,function(item){
                rows.push($scope.getRow(item));
                if (item.subDepartments.length>0){
                    $scope.getRows(item.subDepartments,rows)
                }
            })
        }
        $scope.myDraw=function(){
            google.load("visualization", "1", {packages:["orgchart"]});
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Name');
            data.addColumn('string', 'Manager');
            data.addColumn('string', 'ToolTip');
            //data.addRows([["1", "", ""],["2", "1", ""],["3", "1", ""],["4", "2", ""]]);
            var rows=[];
            rows.push([{
                v:'0',
                f:'<div>公司</div>'
            },'',''])
            $scope.getRows($scope.departments,rows)
            data.addRows(rows);
            var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
            function selectHandler() {
                var selectedItem = chart.getSelection()[0];
                if (selectedItem) {
                    var topping = data.getValue(selectedItem.row, 0);
                    topping=topping!='0'?topping:'';
                    $scope.filterInfos.departmentId=topping
                    $scope.loadContact();
                }
            }
            google.visualization.events.addListener(chart, 'select', selectHandler);
            chart.draw(data, {allowHtml:true,allowCollapse:true,size:"large"});
        }
        //获取联系人的开放电话，地址等
        $scope.getOpenValue=function(array){
            return array?_.join(_.map(_.filter(array,{"name":"开放"}),function(item){return item.value}),"\n"):""
        }
        //筛选
        $scope.departmentFilter=function(item){
            return item.parentDepartmentId==null
        }
        $scope.getDepartmentNameById=function(id){
            var name="";
            id=angular.isNumber(id)?id:parseInt(id)
            _.forEach($scope.departmentsList,function(item){
                if (item.id==id) name=item.name
            })
            return name;
        }
        $scope.getDepartmentById=function(id){
            var dep="";
            id=angular.isNumber(id)?id:parseInt(id)
            _.forEach($scope.departmentsList,function(item){
                if (item.id==id) dep=item
            })
            return dep;
        }
        $scope.clearFilter=function(){
            $scope.filterInfos ={
                name:"",
                departmentId:""
            }
        }
        $scope.clearFilter()
        $scope.containSubDepartment=false;
        $scope.checkIfInDepartment=function(cdid,id){
            cdid=angular.isNumber(cdid)?cdid:parseInt(cdid);
            if (cdid==id) return true;
            var result=false;
            if($scope.containSubDepartment) {
                var dep = $scope.getDepartmentById(id)
                if (dep != null && dep.subDepartments != null && dep.subDepartments.length > 0) {
                    _.forEach(dep.subDepartments, function (item) {
                        result = $scope.checkIfInDepartment(cdid, item.id)
                    })
                }
            }
            return result;
        }
        $scope.contactFilter=function(item){
            if (!(item.innerMembership&&item.innerMembership.indexOf("*")==0||item.talentPoolMembership&&item.talentPoolMembership.indexOf("*")==0||item.relativeMembership&&item.relativeMembership.indexOf("*")==0))return false
            if ($scope.filterInfos.departmentId!=null&&$scope.filterInfos.departmentId!=""&&(item.employeeInfo==null||item.employeeInfo.department==null||!$scope.checkIfInDepartment(item.employeeInfo.department,$scope.filterInfos.departmentId))) return false;
            if ($scope.filterInfos.name!=""){
                if (item.baseInfo.name.indexOf($scope.filterInfos.name)>=0) return true;
                if (item.baseInfo.fixedNumberList&&$scope.getOpenValue(item.baseInfo.fixedNumberList).indexOf($scope.filterInfos.name)>=0) return true;
                if (item.baseInfo.mobileNumberList&&$scope.getOpenValue(item.baseInfo.mobileNumberList).indexOf($scope.filterInfos.name)>=0) return true;
                if (item.baseInfo.emailList&&$scope.getOpenValue(item.baseInfo.emailList).indexOf($scope.filterInfos.name)>=0) return true;
            }
            else
                return true;
            return false
        }

        //选择联系人
        $scope.getParentItem=function(id){
            _.forEach($scope.orgContactList,function(item){
                if(item.id==id){
                    $scope.chain=[item].concat($scope.chain);
                    if (item.employeeInfo!=undefined&&item.employeeInfo.leaderId!=null&&item.employeeInfo.leaderId!=0) $scope.getParentItem(item.employeeInfo.leaderId);
                }
            })
        }
        $scope.getSubordinate=function(id){
            _.forEach($scope.orgContactList,function(item){
                if (item.employeeInfo!=null&&id==item.employeeInfo.leaderId) $scope.subordinate.push(item);
            })
        }
        $scope.changePresentContact=function(id){
            if ($scope.presentContact!=undefined&&id==$scope.presentContact.id&&!$scope.showDepartment) return;
            _.forEach($scope.orgContactList,function(item){
                if (id==item.id) {
                    $scope.presentContact = item;
                    $scope.chain = [item];
                    $scope.subordinate=[];
                    $scope.getSubordinate(id)
                    if (item.employeeInfo != undefined && item.employeeInfo.leaderId != null && item.employeeInfo.leaderId != 0) $scope.getParentItem(item.employeeInfo.leaderId);
                }
            })
            $scope.showDepartment=false;
        }
    })